package com.zitangkou.user.security;

import com.zitangkou.user.domain.IUserDomainService;
import com.zitangkou.user.domain.UserDomain;
import com.zitangkou.common.enums.RespEnum;
import com.zitangkou.common.global.GlobalException;
import com.zitangkou.common.global.UserContent;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.Collection;

/**
 * @author Deng Ningning
 * @date 2020/9/9 23:29
 */
@Component
public class UserDetailsServiceImpl implements UserDetailsService {

    @Autowired
    private IUserDomainService userMapperService;

    @Override
    public MyUserDetails loadUserByUsername(String name) {
        String[] strArray = name.split("#");
        UserDomain userDomain =
                userMapperService.selectOneByConditions(new UserDomain().setEnterpriseId(strArray[0]).setUserAccount(strArray[1]));
        if (userDomain == null) {
            throw new GlobalException(RespEnum.TOKEN_IS_NULL);
        }
        UserContent userContent = new UserContent();
        BeanUtils.copyProperties(userDomain, userContent);
        Collection<GrantedAuthority> authorities = new ArrayList<>();
        return new MyUserDetails(
                userContent.getUserId(),
                userContent.getUserPwd(),
                authorities, userContent);
    }
}
